# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode:
        # 遍历树节点，并且从函数入参 sumVal 中传递路径和
        # 返回的结果如果是 true ，则保留路径，如果是 False 则不需要保留
        def calNode(node: TreeNode, sumVal: int):
            if node is None:
                return False
            # 如果遇到叶子节点，计算路径和是否大于等于 limit ，是则可以保留路径
            if node.left is None and node.right is None:
                return node.val + sumVal >= limit

            left = calNode(node.left, node.val + sumVal)
            right = calNode(node.right, node.val + sumVal)

            if not left:
                node.left = None
            if not right:
                node.right = None

            # 如果左路径和右路径都不保留，那么久不需要保留该路径
            return left or right

        if calNode(root, 0):
            return root
        return None
